#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<assert.h>
#include<string.h>


#define NUM 1024
char lineCommand[NUM];
#define OPT_NUM 64
char* myargv[OPT_NUM];//指针数组
int lastCode = 0;
int lastSig = 0;
int main()
{
    while(1)
     {
        //输出提示符
        printf("用户名@主机号 当前路径# ");
        fflush(stdout);
        //获取用户输入,输入的时候会输入\n
        char* s = fgets(lineCommand,sizeof(lineCommand)-1,stdin);
        assert(s!=NULL);
        //清除最后一个\n
        lineCommand[strlen(lineCommand)-1]=0;
        //printf("test : %s\n",lineCommand);
        //切割字符串
        //"ls -a -l" -> "ls" "-a" "-l"
        myargv[0] = strtok(lineCommand," ");
        int i  = 1;
        //给ls加颜色
        if(myargv[0] != NULL && strcmp(myargv[0],"ls") == 0)
        {
            myargv[i++] = "--color=auto";
        }
        while(myargv[i++] = strtok(NULL," "));//如果没有子字符串要切割，strtok返回NULL，而恰好myargv[end]也一定要= NULL
        if(myargv[0] != NULL && strcmp(myargv[0],"cd") == 0)
        {
            if(myargv[1] != NULL)
            {
                chdir(myargv[1]);
            }
            continue;
        }
        if(myargv[0] != NULL && myargv[1] != NULL && strcmp(myargv[0],"echo") == 0)
        {
            if(strcmp(myargv[1],"$?") == 0)
            {
                printf("%d\n",lastCode);
            }
            else if(strcmp(myargv[1],"$?") != 0)
            {
                for(int i = 1; myargv[i]; i++)
                {
                     printf("%s ",myargv[i]);
                }
                printf("\n");
            }
            else
            {
                printf("%s\n",myargv[1]);
            }
            continue;//重新循环，不执行fork创建子进程
        }
        //测试切割是否成功，条件编译
#ifdef DEBUG 
        for(int i = 0; myargv[i]; i++)
        {
            printf("myargv[%d]: %s\n",i,myargv[i]);
        }
#endif
         //执行命令
        pid_t id = fork();
        assert(id != -1);
        if(id  == 0)
        {
            execvp(myargv[0],myargv);
            exit(1);
        }
        int status = 0;
        pid_t ret =  waitpid(id,&status,0);
        assert(ret > 0);
        lastCode = ((status>>8) & 0xFF);
        lastSig = (status & 0x7F);
     }
}
